package com.jsz.peini.controller.app;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jsz.peini.bean.activity.ActivityInfo;
import com.jsz.peini.bean.activity.ActivityInfoExample;
import com.jsz.peini.bean.activity.ActivityInfoExample.Criteria;
import com.jsz.peini.bean.activity.ActivityUser;
import com.jsz.peini.bean.activity.ActivityUserExample;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.order.OrderInfoExample;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserLogin;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.CommonUtils;
import com.jsz.peini.common.util.NumberFormatUtil;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.mapper.activity.ActivityInfoMapper;
import com.jsz.peini.mapper.activity.ActivityUserMapper;
import com.jsz.peini.mapper.app.SysConfigMapper;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;
import com.jsz.peini.service.advertise.AdvertiseService;

@Controller
public class ActivityInfoController {
	private static final Logger logger = LoggerFactory.getLogger(ActivityInfoController.class);
	@Resource
	private  ActivityInfoMapper activityInfoMapper;
	@Resource
	private ActivityUserMapper activityUserMapper;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private AdvertiseService advertiseService;
	@Resource
	private SysConfigMapper sysConfigMapper;

	/**
	 * 活动列表
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @param sort
	 * @param type
	 * @param page
	 * @param rows
	 * @param userId
	 * @param xpoint
	 * @param ypoint
	 * @return
	 */
//	@ApiOperation("活动列表")
	@RequestMapping(value="/activity/list", method=RequestMethod.GET)
	public String list(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="sort",defaultValue="3",required=false) Integer sort,//排序：1热门推荐；2距离最近；3时间最近
			@RequestParam(value="type",required=false) Integer type,  //0发起中；1活动中；-1已结束;100我参加的
			@RequestParam(value="page",defaultValue="1",required=false) Integer page,
			@RequestParam(value="rows",defaultValue="10",required=false) Integer rows,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="xpoint",required=true) String xpoint,
			@RequestParam(value="ypoint",required=true) String ypoint
			){
		try {
			Date date=new Date();
			if(type != null && type == 999){
				type = null;
			}
			
			com.alibaba.fastjson.JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj.toJSONString();
			}
			userId = obj.getString("userId");
			
			request.getSession().setAttribute("userId", userId);
			request.getSession().setAttribute("xpoint", xpoint);
			request.getSession().setAttribute("ypoint", ypoint);
			
			List<String> idList = new ArrayList<String>();
			
			//我参加的所有活动
			ActivityUserExample userExample = new ActivityUserExample();
			userExample.createCriteria().andUserIdEqualTo(userId);
			List<ActivityUser> activityUsers = activityUserMapper.selectByExample(userExample);
			for (ActivityUser activityUser : activityUsers) {
				idList.add(activityUser.getAcId());
			}
			
			ActivityInfoExample example = new ActivityInfoExample();			
			if(idList.size() == 0){
				request.getSession().setAttribute("regCnt", 0);
			}else{
				example = new ActivityInfoExample();			
				example.createCriteria().andSignStartTimeLessThanOrEqualTo(date).andEndTimeGreaterThanOrEqualTo(date).andAcIdIn(idList);
				int regCnt = activityInfoMapper.countByExample(example);
				request.getSession().setAttribute("regCnt", regCnt);
			}
			
			example = new ActivityInfoExample();
			Criteria criteria = example.createCriteria();
			criteria.andSignStartTimeLessThanOrEqualTo(date);
			//criteria.andEndTimeGreaterThanOrEqualTo(date);
			if(type != null && type != 100){
//				criteria.andAcTypeEqualTo(type);
				if(type==0)
				{
					criteria.andSignStartTimeLessThanOrEqualTo(date);
					criteria.andSignEndTimeGreaterThanOrEqualTo(date);
				}
				else if(type==1)
				{
					criteria.andStartTimeLessThanOrEqualTo(date);
					criteria.andEndTimeGreaterThanOrEqualTo(date);
				}
				if(type==2)
				{
					criteria.andSignEndTimeLessThanOrEqualTo(date);
					criteria.andStartTimeGreaterThanOrEqualTo(date);
				}
				if(type == -1){
					criteria.andEndTimeLessThanOrEqualTo(date);
				}
			}else if(type != null && type == 100){
				criteria.andAcIdIn(idList);
			}
			//criteria.andAcStatusGreaterThanOrEqualTo(0);
//			criteria.andAcStatusNotEqualTo(0);
			if(sort == 3){
				example.setOrderByClause("start_time desc");
			}else if(sort == 1){
				example.setOrderByClause("pageViews desc");
			}
			
			List<ActivityInfo> list = new ArrayList<ActivityInfo>();
			if(sort != 2){
				Page<?> p = PageHelper.startPage(page,rows);
				list = activityInfoMapper.selectByExampleWithBLOBs(example);
				for (int i = 0; i < list.size(); i++) {
					ActivityInfo act = list.get(i);
					/*if(act.getStartTime().before(new Date()) && act.getEndTime().after(new Date()) && (act.getPersonMinNum() == 0 || act.getPersonMaxNum() <= act.getRegUserCnt())){
						if(act.getAcStatus() == 0){
							act.setAcStatus(1);
							activityInfoMapper.updateByPrimaryKeyWithBLOBs(act);
						}
					}else if(act.getEndTime().before(new Date()) && act.getAcStatus() != -1){
						act.setAcStatus(-1);
						activityInfoMapper.updateByPrimaryKeyWithBLOBs(act);
					}*/
					if(idList.contains(act.getAcId())){
						act.setIsReg(1);
					}else{
						act.setIsReg(0);
					}
					if(date.getTime()>act.getSignStartTime().getTime()&&date.getTime()<act.getStartTime().getTime())
					{
						if(act.getIsperson()==1)
						{
							if(act.getRegUserCnt()==act.getPersonMaxNum())
							{
								act.setAcStatus(4);
							}
							else
							{
								act.setAcStatus(0);
							}
						}
						else
						{
							act.setAcStatus(0);
						}
					}
					List<byte[]> list1 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+act.getAcId()).getBytes(), userId.getBytes());
					if(list1.size()>0&& list1.get(0) != null)
					{
						act.setAcStatus(5);
					}
					if(date.getTime()>act.getSignEndTime().getTime()&&date.getTime()<act.getStartTime().getTime())
					{
						act.setAcStatus(2);
					}
					if(date.getTime()>act.getStartTime().getTime()&&date.getTime()<act.getEndTime().getTime())
					{
						act.setAcStatus(1);
					}
					if(date.getTime()>act.getEndTime().getTime())
					{
						act.setAcStatus(-1);
					}
					
					com.alibaba.fastjson.JSONObject object=PeiniUtils.getProviceById(act.getProvinceId());
					com.alibaba.fastjson.JSONObject object1=PeiniUtils.getProviceById(act.getCityId());
					com.alibaba.fastjson.JSONObject object2=PeiniUtils.getProviceById(act.getDistId());
					act.setDescribe(object.getString("name").toString()+object1.getString("name").toString()+object2.getString("name").toString());
					list.set(i, act);
				}
				request.setAttribute("list", list);
			}else{
				list = activityInfoMapper.selectByExampleWithBLOBs(example);
			}
			
			
			HashMap<String, Integer> map = new HashMap<String, Integer>();
			
			if(sort == 2){//距离最近
				ActivityInfo [] aa=new ActivityInfo[list.size()];
				for(int a=0;a<list.size();a++)
				{
					aa[a]=list.get(a);
				}
				for (int i = 0; i < aa.length; i++) {					
					for (int j = 0; j+1 < aa.length-i; j++) {
						ActivityInfo aaj = aa[j];
						ActivityInfo aaj1 = aa[j+1];
						/*if(aaj.getStartTime().before(new Date()) && aaj.getEndTime().after(new Date()) && (aaj.getPersonMinNum() == 0 || aaj.getPersonMaxNum() <= aaj.getRegUserCnt())){
							if(aaj.getAcStatus() == 0){
								aaj.setAcStatus(1);
								activityInfoMapper.updateByPrimaryKeyWithBLOBs(aaj);
							}
						}else if(aaj.getEndTime().before(new Date()) && aaj.getAcStatus() != -1){
							aaj.setAcStatus(-1);
							activityInfoMapper.updateByPrimaryKeyWithBLOBs(aaj);
						}*/
						
						if(idList.contains(aaj.getAcId())){
							aaj.setIsReg(1);
						}else{
							aaj.setIsReg(0);
						}
						if(idList.contains(aaj1.getAcId())){
							aaj1.setIsReg(1);
						}else{
							aaj1.setIsReg(0);
						}
//						Date date=new Date();
						if(date.getTime()>aaj1.getSignStartTime().getTime()&&date.getTime()<aaj1.getSignEndTime().getTime())
						{
							if(aaj1.getIsperson()==1)
							{
								if(aaj1.getRegUserCnt()==aaj1.getPersonMaxNum())
								{
									aaj1.setAcStatus(4);
								}
								else
								{
									aaj1.setAcStatus(0);
								}
							}
							else
							{
								aaj1.setAcStatus(0);
							}
						}
						List<byte[]> list1 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+aaj1.getAcId()).getBytes(), userId.getBytes());
						if(list1.size()>0&& list1.get(0) != null)
						{
							aaj1.setAcStatus(5);
						}
						if(date.getTime()>aaj1.getSignEndTime().getTime()&&date.getTime()<aaj1.getStartTime().getTime())
						{
							aaj1.setAcStatus(2);
						}
						if(date.getTime()>aaj1.getStartTime().getTime()&&date.getTime()<aaj1.getEndTime().getTime())
						{
							aaj1.setAcStatus(1);
						}
						if(date.getTime()>aaj1.getEndTime().getTime())
						{
							aaj1.setAcStatus(-1);
						}
						if(date.getTime()>aaj.getSignStartTime().getTime()&&date.getTime()<aaj.getSignEndTime().getTime())
						{
							if(aaj.getIsperson()==1)
							{
								if(aaj.getRegUserCnt()==aaj.getPersonMaxNum())
								{
									aaj.setAcStatus(4);
								}
								else
								{
									aaj.setAcStatus(0);
								}
							}
							else
							{
								aaj.setAcStatus(0);
							}
						}
						List<byte[]> list2 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+aaj.getAcId()).getBytes(), userId.getBytes());
						if(list2.size()>0&& list2.get(0) != null)
						{
							aaj.setAcStatus(5);
						}
						if(date.getTime()>aaj.getSignEndTime().getTime()&&date.getTime()<aaj.getStartTime().getTime())
						{
							aaj.setAcStatus(2);
						}
						if(date.getTime()>aaj.getStartTime().getTime()&&date.getTime()<aaj.getEndTime().getTime())
						{
							aaj.setAcStatus(1);
						}
						if(date.getTime()>aaj.getEndTime().getTime())
						{
							aaj.setAcStatus(-1);
						}
						com.alibaba.fastjson.JSONObject object3=PeiniUtils.getProviceById(aaj1.getProvinceId());
						com.alibaba.fastjson.JSONObject object1=PeiniUtils.getProviceById(aaj1.getCityId());
						com.alibaba.fastjson.JSONObject object2=PeiniUtils.getProviceById(aaj1.getDistId());
						aaj1.setDescribe(object3.getString("name").toString()+object1.getString("name").toString()+object2.getString("name").toString());
						com.alibaba.fastjson.JSONObject object4=PeiniUtils.getProviceById(aaj.getProvinceId());
						com.alibaba.fastjson.JSONObject object5=PeiniUtils.getProviceById(aaj.getCityId());
						com.alibaba.fastjson.JSONObject object6=PeiniUtils.getProviceById(aaj.getDistId());
						aaj.setDescribe(object4.getString("name").toString()+object5.getString("name").toString()+object6.getString("name").toString());
						int jreu = 0;
						int j1reu = 0;
						if(map.containsKey(aaj.getAcId())){
							jreu = map.get(aaj.getAcId());
						}else{
							jreu = CommonUtils.contrastMap(xpoint, ypoint, aaj.getXpoint(), aaj.getYpoint());
						}
						if(map.containsKey(aaj1.getAcId())){
							jreu = map.get(aaj1.getAcId());
						}else{
							j1reu = CommonUtils.contrastMap(xpoint, ypoint, aaj1.getXpoint(), aaj1.getYpoint());
						}
						
						if(jreu < j1reu){//比较交换相邻元素 
							ActivityInfo temp; 
							temp=aa[j]; 
							aa[j]=aa[j+1]; 
							aa[j+1]=temp; 
						}
					}
				}
				
				int totalPage = aa.length/rows;
				
				if(page > totalPage){
					page = totalPage;
				}
				if((page*rows)>totalPage){
					aa = Arrays.copyOfRange(aa, (page-1)*rows, aa.length-1);
				}else{
					aa = Arrays.copyOfRange(aa, (page-1)*rows, page*rows-1);
				}
				
				request.setAttribute("list", aa);
			}
			
			example = new ActivityInfoExample();	
			example.createCriteria().andStartTimeLessThanOrEqualTo(date).andEndTimeGreaterThanOrEqualTo(date);
			int cnt = activityInfoMapper.countByExample(example);
			request.getSession().setAttribute("totalCnt", cnt);
			
			List<LinkedHashMap<String,Object>> advertiseList=advertiseService.getAdvertise(5);
			request.setAttribute("ads", advertiseList);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		
		return "activity/list";
	}
	
	/**
	 * 活动列表数据
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @param sort
	 * @param type
	 * @param page
	 * @param rows
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/activity/listJson")
	public String listJson(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="sort",defaultValue="3") Integer sort,//排序：1热门推荐；2距离最近；3时间最近4创建时间
			@RequestParam(value="type",required=false) Integer type,  //0发起中；1活动中；-1已结束;100我参加的
			@RequestParam(value="page",defaultValue="1") Integer page,
			@RequestParam(value="rows",defaultValue="10") Integer rows
			){
		JSONObject object = new JSONObject();
		try {
			Date date=new Date();
			if(type != null && type == 999){
				type = null;
			}
			
			String xpoint = request.getParameter("xpoint");
			String ypoint = request.getParameter("ypoint");
			String userId = request.getParameter("userId");
			
			List<String> idList = new ArrayList<String>();
			
			ActivityUserExample userExample = new ActivityUserExample();
			userExample.createCriteria().andUserIdEqualTo(userId);
			List<ActivityUser> activityUsers = activityUserMapper.selectByExample(userExample);
			for (ActivityUser activityUser : activityUsers) {
				idList.add(activityUser.getAcId());
			}
			
			ActivityInfoExample example = new ActivityInfoExample();			
			
			if(idList.size() == 0){
				request.getSession().setAttribute("regCnt", 0);
			}else{
				example = new ActivityInfoExample();			
				example.createCriteria().andSignStartTimeLessThanOrEqualTo(date).andEndTimeGreaterThanOrEqualTo(date).andAcIdIn(idList);
				int regCnt = activityInfoMapper.countByExample(example);
				request.getSession().setAttribute("regCnt", regCnt);
			}
			
			example = new ActivityInfoExample();
			Criteria criteria = example.createCriteria();
			criteria.andSignStartTimeLessThanOrEqualTo(date);
			//criteria.andEndTimeGreaterThanOrEqualTo(date);
			if(type != null && type != 100){
				if(type==0)
				{
					criteria.andSignStartTimeLessThanOrEqualTo(date);
					criteria.andSignEndTimeGreaterThanOrEqualTo(date);
				}
				else if(type==1)
				{
					criteria.andStartTimeLessThanOrEqualTo(date);
					criteria.andEndTimeGreaterThanOrEqualTo(date);
				}
				if(type==2)
				{
					criteria.andSignEndTimeLessThanOrEqualTo(date);
					criteria.andStartTimeGreaterThanOrEqualTo(date);
				}
				if(type == -1){
					criteria.andEndTimeLessThanOrEqualTo(date);
				}
//				criteria.andAcTypeEqualTo(type);
			}else if(type != null && type == 100){
				if(idList.size()>0)
				{
					criteria.andAcIdIn(idList);
				}
					
				else
				{
					criteria.andAcIdIsNull();
				}
				
			}
//			criteria.andAcStatusNotEqualTo(0);
			if(sort == 3){
				example.setOrderByClause("start_time desc");
			}else if(sort == 1){
				example.setOrderByClause("pageViews desc");
			}
			
			JSONArray array = new JSONArray();
			List<ActivityInfo> list = new ArrayList<ActivityInfo>();
			if(sort != 2){
				Page<?> p = PageHelper.startPage(page,rows);
				list = activityInfoMapper.selectByExampleWithBLOBs(example);
				if(list.size()>0)
				{
					for (ActivityInfo act : list) {
						if(act.getRegUserCnt() == null){
							act.setRegUserCnt(0);
						}
//						if((act.getPersonMinNum() == 0 || act.getPersonMaxNum() <= act.getRegUserCnt())){
//							if(act.getAcStatus() == 0){
//								act.setAcStatus(1);
//								activityInfoMapper.updateByPrimaryKeyWithBLOBs(act);
//							}
//						}else if(act.getEndTime().before(new Date()) && act.getAcStatus() != -1){
//							act.setAcStatus(-1);
//							activityInfoMapper.updateByPrimaryKeyWithBLOBs(act);
//						}
						if(date.getTime()>act.getSignStartTime().getTime()&&date.getTime()<act.getStartTime().getTime())
						{
							if(act.getIsperson()==1)
							{
								if(act.getRegUserCnt()==act.getPersonMaxNum())
								{
									act.setAcStatus(4);
								}
								else
								{
									act.setAcStatus(0);
								}
							}
							else
							{
								act.setAcStatus(0);
							}
							
						}
						List<byte[]> list1 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+act.getAcId()).getBytes(), userId.getBytes());
						if(list1.size()>0&& list1.get(0) != null)
						{
							act.setAcStatus(5);
						}
						if(date.getTime()>act.getSignEndTime().getTime()&&date.getTime()<act.getStartTime().getTime())
						{
							act.setAcStatus(2);
						}
						if(date.getTime()>act.getStartTime().getTime()&&date.getTime()<act.getEndTime().getTime())
						{
							act.setAcStatus(1);
						}
						if(date.getTime()>act.getEndTime().getTime())
						{
							act.setAcStatus(-1);
						}
						
						com.alibaba.fastjson.JSONObject object3=PeiniUtils.getProviceById(act.getProvinceId());
						com.alibaba.fastjson.JSONObject object1=PeiniUtils.getProviceById(act.getCityId());
						com.alibaba.fastjson.JSONObject object2=PeiniUtils.getProviceById(act.getDistId());
						act.setDescribe(object3.getString("name").toString()+object1.getString("name").toString()+object2.getString("name").toString());
				
					}
					array = JSONArray.fromObject(list);
					for (int i = 0; i < array.size(); i++) {
						JSONObject obj = array.getJSONObject(i);
						obj.put("acFee", NumberFormatUtil.format2RMB(obj.getDouble("acFee")/100));
						if(idList.contains(obj.getString("acId"))){
							obj.put("isReg", 1);
						}else{
							obj.put("isReg", 0);
						}
						obj.put("acImg", PeiniUtils.IMGHOST+obj.getString("acImg"));
						array.set(i, obj);
					}
					
					if(p.getTotal()/rows+1 < page){
						object.put("lists", new JSONArray());
					}else{
						object.put("lists", array);
					}
				}
				else
				{
					object.put("lists", array);
				}

			}else{
				list = activityInfoMapper.selectByExampleWithBLOBs(example);
			}
			HashMap<String, Integer> map = new HashMap<String, Integer>();
			if(sort == 2){//距离最近
//				ActivityInfo [] aa = (ActivityInfo[]) list.toArray();
//				ActivityInfo [] aa1=new ActivityInfo[10];
				ActivityInfo [] aa=new ActivityInfo[list.size()];
				for(int a=0;a<list.size();a++)
				{
					aa[a]=list.get(a);
				}
				for (int i = 0; i < aa.length; i++) {	
					for (int j = 0; j+1 < aa.length-i; j++) {
						ActivityInfo aaj = aa[j];
						ActivityInfo aaj1 = aa[j+1];
						
//						if(aaj.getStartTime().before(new Date()) && aaj.getEndTime().after(new Date()) && (aaj.getPersonMinNum() == 0 || aaj.getPersonMaxNum() <= aaj.getRegUserCnt())){
//							if(aaj.getAcStatus() == 0){
//								aaj.setAcStatus(1);
//								activityInfoMapper.updateByPrimaryKeyWithBLOBs(aaj);
//							}
//						}else if(aaj.getEndTime().before(new Date()) && aaj.getAcStatus() != -1){
//							aaj.setAcStatus(-1);
//							activityInfoMapper.updateByPrimaryKeyWithBLOBs(aaj);
//						}
						if(idList.contains(aaj.getAcId())){
							aaj.setIsReg(1);
						}else{
							aaj.setIsReg(0);
						}
						if(idList.contains(aaj1.getAcId())){
							aaj1.setIsReg(1);
						}else{
							aaj1.setIsReg(0);
						}
//						Date date=new Date();
						if(date.getTime()>aaj1.getSignStartTime().getTime()&&date.getTime()<aaj1.getSignEndTime().getTime())
						{
							if(aaj1.getIsperson()==1)
							{
								if(aaj1.getRegUserCnt()==aaj1.getPersonMaxNum())
								{
									aaj1.setAcStatus(4);
								}
								else
								{
									aaj1.setAcStatus(0);
								}
							}
							else
							{
								aaj1.setAcStatus(0);
							}
						}
						List<byte[]> list1 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+aaj1.getAcId()).getBytes(), userId.getBytes());
						if(list1.size()>0&& list1.get(0) != null)
						{
							aaj1.setAcStatus(5);
						}
						if(date.getTime()>aaj1.getSignEndTime().getTime()&&date.getTime()<aaj1.getStartTime().getTime())
						{
							aaj1.setAcStatus(2);
						}
						if(date.getTime()>aaj1.getStartTime().getTime()&&date.getTime()<aaj1.getEndTime().getTime())
						{
							aaj1.setAcStatus(1);
						}
						if(date.getTime()>aaj1.getEndTime().getTime())
						{
							aaj1.setAcStatus(-1);
						}
						if(date.getTime()>aaj.getSignStartTime().getTime()&&date.getTime()<aaj.getSignEndTime().getTime())
						{
							if(aaj.getIsperson()==1)
							{
								if(aaj.getRegUserCnt()==aaj.getPersonMaxNum())
								{
									aaj.setAcStatus(4);
								}
								else
								{
									aaj.setAcStatus(0);
								}
							}
							else
							{
								aaj.setAcStatus(0);
							}
						}
						List<byte[]> list2 = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+aaj.getAcId()).getBytes(), userId.getBytes());
						if(list2.size()>0&& list2.get(0) != null)
						{
							aaj.setAcStatus(5);
						}
						if(date.getTime()>aaj.getSignEndTime().getTime()&&date.getTime()<aaj.getStartTime().getTime())
						{
							aaj.setAcStatus(2);
						}
						if(date.getTime()>aaj.getStartTime().getTime()&&date.getTime()<aaj.getEndTime().getTime())
						{
							aaj.setAcStatus(1);
						}
						if(date.getTime()>aaj.getEndTime().getTime())
						{
							aaj.setAcStatus(-1);
						}
						com.alibaba.fastjson.JSONObject object3=PeiniUtils.getProviceById(aaj1.getProvinceId());
						com.alibaba.fastjson.JSONObject object1=PeiniUtils.getProviceById(aaj1.getCityId());
						com.alibaba.fastjson.JSONObject object2=PeiniUtils.getProviceById(aaj1.getDistId());
						aaj1.setDescribe(object3.getString("name").toString()+object1.getString("name").toString()+object2.getString("name").toString());
						com.alibaba.fastjson.JSONObject object4=PeiniUtils.getProviceById(aaj.getProvinceId());
						com.alibaba.fastjson.JSONObject object5=PeiniUtils.getProviceById(aaj.getCityId());
						com.alibaba.fastjson.JSONObject object6=PeiniUtils.getProviceById(aaj.getDistId());
						aaj.setDescribe(object4.getString("name").toString()+object5.getString("name").toString()+object6.getString("name").toString());
						int jreu = 0;
						int j1reu = 0;
						if(map.containsKey(aaj.getAcId())){
							jreu = map.get(aaj.getAcId());
						}else{
							jreu = CommonUtils.contrastMap(xpoint, ypoint, aaj.getXpoint(), aaj.getYpoint());
						}
						if(map.containsKey(aaj1.getAcId())){
							jreu = map.get(aaj1.getAcId());
						}else{
							j1reu = CommonUtils.contrastMap(xpoint, ypoint, aaj1.getXpoint(), aaj1.getYpoint());
						}
						
						if(jreu < j1reu){//比较交换相邻元素 
							ActivityInfo temp; 
							temp=aa[j]; 
							aa[j]=aa[j+1]; 
							aa[j+1]=temp; 
						}
					}
				}
				int totalPage=0;
				if(aa.length%rows>0)
				{
					 totalPage = aa.length/rows+1;
				}
				else
				{
					totalPage = aa.length/rows;
				}
				
				if(page > totalPage){
					page = totalPage;
				}
				if((page*rows)>totalPage){
					aa = Arrays.copyOfRange(aa, (page-1)*rows, aa.length-1);
				}else{
					aa = Arrays.copyOfRange(aa, (page-1)*rows, page*rows-1);
				}
				array = JSONArray.fromObject(aa);
				for (int i = 0; i < array.size(); i++) {
					JSONObject obj = array.getJSONObject(i);
					obj.put("acFee", NumberFormatUtil.format2RMB(obj.getDouble("acFee")/100));
					obj.put("acImg", PeiniUtils.IMGHOST+obj.getString("acImg"));
					array.set(i, obj);
				}
				//request.setAttribute("list", aa);
				object.put("lists", array);
			}
			
			example = new ActivityInfoExample();	
			example.createCriteria().andStartTimeLessThanOrEqualTo(date).andEndTimeGreaterThanOrEqualTo(date);
			int cnt = activityInfoMapper.countByExample(example);
			request.getSession().setAttribute("totalCnt", cnt);
			
			object.put("code", 1);
			object.put("msg", "");
		} catch (Exception e) {
			object.put("code", 0);
			object.put("msg", "");
			logger.error(e.getMessage(),e);
		}
		
		return object.toString();
	}
	
	/**
	 * 活动详情
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/activity/detail")
	public String detail(HttpServletRequest request,HttpServletResponse response){
		Date date=new Date();
		String id = request.getParameter("id");
		String userId = request.getParameter("userId");
		ActivityInfo info = activityInfoMapper.selectByPrimaryKey(id);
		info.setPageviews((info.getPageviews() == null ? 0 : info.getPageviews())+1);
		if(date.getTime()>info.getSignStartTime().getTime()&&date.getTime()<info.getStartTime().getTime())
		{
			if(info.getIsperson()==1)
			{
				if(info.getRegUserCnt()==info.getPersonMaxNum())
				{
					info.setAcStatus(4);
				}
				else
				{
					info.setAcStatus(0);
				}
			}
			else
			{
				info.setAcStatus(0);
			}
			
		}
		if(date.getTime()>info.getSignEndTime().getTime()&&date.getTime()<info.getStartTime().getTime())
		{
			info.setAcStatus(2);
		}
		if(date.getTime()>info.getStartTime().getTime()&&date.getTime()<info.getEndTime().getTime())
		{
			info.setAcStatus(1);
		}
		if(date.getTime()>info.getEndTime().getTime())
		{
			info.setAcStatus(-1);
		}
		/*if(info.getStartTime().before(new Date()) && info.getEndTime().after(new Date()) && (info.getPersonMinNum() == 0 || info.getPersonMaxNum() <= info.getRegUserCnt())){
			if(info.getAcStatus() == 0){
				info.setAcStatus(1);
			}
		}else if(info.getEndTime().before(new Date()) && info.getAcStatus() != -1){
			info.setAcStatus(-1);
		}*/
		
//		activityInfoMapper.updateByPrimaryKeyWithBLOBs(info);
//		if(date.getTime()<info.getSignEndTime().getTime())
//		{
//			if(info.getRegUserCnt()==info.getPersonMaxNum())
//			{
//				info.setAcStatus(4);
//			}
//		}
//		else
//		{
//			info.setAcStatus(3);
//		}
		List<byte[]> list = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+info.getAcId()).getBytes(), userId.getBytes());
		if(list.size()>0&& list.get(0) != null)
		{
			info.setAcStatus(5);
		}
		com.alibaba.fastjson.JSONObject object3=PeiniUtils.getProviceById(info.getProvinceId());
		com.alibaba.fastjson.JSONObject object1=PeiniUtils.getProviceById(info.getCityId());
		com.alibaba.fastjson.JSONObject object2=PeiniUtils.getProviceById(info.getDistId());
		info.setDescribe(object3.getString("name").toString()+object1.getString("name").toString()+object2.getString("name").toString());
		request.setAttribute("info", info);
		ActivityUserExample userExample1 = new ActivityUserExample();
		userExample1.createCriteria().andAcIdEqualTo(id);
		userExample1.setOrderByClause(" reg_time desc");
		List<ActivityUser> activityUserss = activityUserMapper.selectByExample(userExample1);
		JSONArray array=new JSONArray();
		if(activityUserss.size()>0)
		{
			for(ActivityUser user:activityUserss)
			{
				String configPath = PeiniUtils.IMGHOST;
				UserInfo userinfo=userInfoMapper.selectByPrimaryKey(user.getUserId());
				
				JSONObject obj=new JSONObject();
				
				if(userinfo == null){
					obj.put("image","images/ic_nan.png");
				}else{
					if(userinfo.getImageHead()!=null&&userinfo.getImageHead()!="")
					{
						obj.put("image", configPath+userinfo.getImageHead());
					}
					else
					{
						if(userinfo.getSex()==1)
						{
							obj.put("image","images/ic_nan.png");
						}
						else
						{
							 obj.put("image", "images/ic_nv.png");
						}
					}
				}
				
				array.add(obj);
			}
			
		}
		
		request.setAttribute("userimages", array);
		ActivityUserExample userExample = new ActivityUserExample();
		userExample.createCriteria().andAcIdEqualTo(id);
		List<ActivityUser> activityUsers = activityUserMapper.selectByExample(userExample);
		if(activityUsers.size() == 0){
			request.setAttribute("isReg", 0);
		}else{
			request.setAttribute("isReg", 1);
		}
		
		return "activity/detail";
	}
	
	/**
	 * 活动报名
	 * @author Han Guohong
	 * @param request
	 * @param userId
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/activity/register")
	public Object register(HttpServletRequest request,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="acId") String acId//活动id 
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			com.alibaba.fastjson.JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			String regCnt = RedisUtil.get(RedisConstants.ACTIVITY+acId);
			if(StringUtils.isBlank(regCnt)){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "报名已经结束");
				return infoMap;
			}
			
			//从缓存查询有没有报名
			List<byte[]> list = RedisUtil.hmget((RedisConstants.ACTIVITY_USER+acId).getBytes(), userId.getBytes());
			if(list.size() > 0 && list.get(0) != null){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "该活动您已经报过名了，不允许重复报名");
				return infoMap;
			}
			/*Set<byte[]> keys = RedisUtil.hkeys(RedisConstants.ACTIVITY_USER.getBytes());
			for (byte[] bs : keys) {
				String str = SerializeUtil.unserialize(bs).toString();
				if(str.equals(userId)){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "该活动您已经报过名了，不允许重复报名");
					return infoMap;
				}
			}*/
			
			Integer rCnt = Integer.parseInt(regCnt);
			ActivityInfo info = activityInfoMapper.selectByPrimaryKey(acId);
			if(info == null){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "参数错误");
				return infoMap;
			}
			Date date=new Date();
			if(date.getTime()>info.getSignEndTime().getTime()){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "报名已经结束");
				return infoMap;
			}
			
			if(info.getAcFee() == 0){
				if(info.getIsperson()==1)
				{
					Integer totalCnt = info.getPersonMaxNum();
					if(rCnt < totalCnt){
						Jedis redis = RedisUtil.getRedis();
						redis.watch(RedisConstants.ACTIVITY+acId);
						Transaction trsn = redis.multi();
						trsn.set(RedisConstants.ACTIVITY+acId, String.valueOf(rCnt));
						List<Object> objList = trsn.exec();
						if(objList != null && objList.size() > 0){
							
							//报名成功，将报名数据写入缓存
							RedisUtil.set(RedisConstants.ACTIVITY+acId,String.valueOf(rCnt+1));
							info.setRegUserCnt(rCnt + 1);
//							if(info.getPersonMinNum() <= (rCnt+1) && info.getAcStatus() == 0){
//								info.setAcStatus(1);
//							}
//							
//							if(info.getPersonMaxNum() == (rCnt + 1) && info.getAcStatus() == 1){
//								info.setAcStatus(-1);
//							}
							if(date.getTime()>info.getSignStartTime().getTime()&&date.getTime()<info.getStartTime().getTime())
							{
								if(info.getIsperson()==1)
								{
									if(info.getPersonMaxNum()==(rCnt + 1))
									{
										info.setAcStatus(4);
									}
									else
									{
										info.setAcStatus(0);
									}
								}
								else
								{
									info.setAcStatus(0);
								}
								
							}
							if(date.getTime()>info.getSignEndTime().getTime()&&date.getTime()<info.getStartTime().getTime())
							{
								info.setAcStatus(2);
							}
							if(date.getTime()>info.getStartTime().getTime()&&date.getTime()<info.getEndTime().getTime())
							{
								info.setAcStatus(1);
							}
							if(date.getTime()>info.getEndTime().getTime())
							{
								info.setAcStatus(-1);
							}
							activityInfoMapper.updateByPrimaryKey(info);
							ActivityUser acUser = new ActivityUser();
							acUser.setAcId(acId);
							acUser.setUserId(userId);
							acUser.setRegId(UUID.randomUUID().toString().replace("-", ""));
							acUser.setRegTime(new Date());
							acUser.setActivityInfo(info);
							activityUserMapper.insertSelective(acUser);
							
							//将数据插入redis缓存
							HashMap<byte[], byte[]> acUserMap = new HashMap<byte[], byte[]>();
							acUserMap.put(userId.getBytes(), SerializeUtil.serialize(acUser));
							RedisUtil.hmset((RedisConstants.ACTIVITY_USER+acId).getBytes(), acUserMap);
							
							//将数据放入数据库待处理队列
							/*activityUserMapper.insertSelective(acUser);
							ActivityInfo info = acUser.getActivityInfo();
							activityInfoMapper.updateByPrimaryKey(info);*/
//							PeiniUtils.activityUserList.add(acUser);
							
							//对接上线活动大屏幕
							/*List<Integer> ids = new ArrayList<Integer>();
							ids.add(4);
							ids.add(5);
							ids.add(6);
							ids.add(7);
							SysConfigExample configExample = new SysConfigExample();
							configExample.createCriteria().andIdIn(ids);
							List<SysConfig> confList = sysConfigMapper.selectByExample(configExample);
							for (SysConfig sysConfig : confList) {
								if(acId.equals(sysConfig.getConval())){
									ActivityUser activityUser = new ActivityUser();
									activityUser.setAcId(acId);
									activityUser.setUserId(userId);
									RedisUtil.lpush(RedisConstants.ACTIVITY_LETAI.getBytes(), SerializeUtil.serialize(activityUser));
								}
							}*/
							
							infoMap.put("orderIdStr", "");
							infoMap.put("resultCode", Constants.SUCCESS);
							infoMap.put("resultDesc", Constants.SUCCESS_DESC);
							return infoMap;
						}else{
							infoMap.put("resultCode", Constants.FAIL);
							infoMap.put("resultDesc", "由于报名人数过多报名失败，请重试！");
							return infoMap;
						}
					}else{
						infoMap.put("resultCode", Constants.FAIL);
						infoMap.put("resultDesc", "报名人数已经满额，不允许报名！");
						return infoMap;
					}
				}
				else
				{
					Jedis redis = RedisUtil.getRedis();
					redis.watch(RedisConstants.ACTIVITY+acId);
					Transaction trsn = redis.multi();
					trsn.set(RedisConstants.ACTIVITY+acId, String.valueOf(rCnt));
					List<Object> objList = trsn.exec();
					if(objList != null && objList.size() > 0){
						
						//报名成功，将报名数据写入缓存
						RedisUtil.set(RedisConstants.ACTIVITY+acId,String.valueOf(rCnt+1));
						info.setRegUserCnt(rCnt + 1);
						if(date.getTime()>info.getSignStartTime().getTime()&&date.getTime()<info.getStartTime().getTime())
						{
							if(info.getIsperson()==1)
							{
								if(info.getPersonMaxNum()==(rCnt + 1))
								{
									info.setAcStatus(4);
								}
								else
								{
									info.setAcStatus(0);
								}
							}
							else
							{
								info.setAcStatus(0);
							}
							
						}
						if(date.getTime()>info.getSignEndTime().getTime()&&date.getTime()<info.getStartTime().getTime())
						{
							info.setAcStatus(2);
						}
						if(date.getTime()>info.getStartTime().getTime()&&date.getTime()<info.getEndTime().getTime())
						{
							info.setAcStatus(1);
						}
						if(date.getTime()>info.getEndTime().getTime())
						{
							info.setAcStatus(-1);
						}
//						if(info.getPersonMinNum() <= (rCnt+1) && info.getAcStatus() == 0){
//							info.setAcStatus(1);
//						}
//						if(info.getPersonMaxNum() == (rCnt + 1) && info.getAcStatus() == 1){
//							info.setAcStatus(-1);
//						}
						
						activityInfoMapper.updateByPrimaryKey(info);
						
						ActivityUser acUser = new ActivityUser();
						acUser.setAcId(acId);
						acUser.setUserId(userId);
						acUser.setRegId(UUID.randomUUID().toString().replace("-", ""));
						acUser.setRegTime(new Date());
						acUser.setActivityInfo(info);
						activityUserMapper.insertSelective(acUser);
						//将数据插入redis缓存
						HashMap<byte[], byte[]> acUserMap = new HashMap<byte[], byte[]>();
						acUserMap.put(userId.getBytes(), SerializeUtil.serialize(acUser));
						RedisUtil.hmset((RedisConstants.ACTIVITY_USER+acId).getBytes(), acUserMap);
						
						//将数据放入数据库待处理队列
						/*activityUserMapper.insertSelective(acUser);
						ActivityInfo info = acUser.getActivityInfo();
						activityInfoMapper.updateByPrimaryKey(info);*/
//						PeiniUtils.activityUserList.add(acUser);
						
						//对接上线活动大屏幕
						/*List<Integer> ids = new ArrayList<Integer>();
						ids.add(4);
						ids.add(5);
						ids.add(6);
						ids.add(7);
						SysConfigExample configExample = new SysConfigExample();
						configExample.createCriteria().andIdIn(ids);
						List<SysConfig> confList = sysConfigMapper.selectByExampleWithBLOBs(configExample);
						for (SysConfig sysConfig : confList) {
							if(acId.equals(sysConfig.getConval())){
								ActivityUser activityUser = new ActivityUser();
								activityUser.setAcId(acId);
								activityUser.setUserId(userId);
								RedisUtil.lpush(RedisConstants.ACTIVITY_LETAI.getBytes(), SerializeUtil.serialize(activityUser));
							}
						}*/
						
						infoMap.put("orderIdStr", "");
						infoMap.put("resultCode", Constants.SUCCESS);
						infoMap.put("resultDesc", Constants.SUCCESS_DESC);
						return infoMap;
					}else{
						infoMap.put("resultCode", Constants.FAIL);
						infoMap.put("resultDesc", "由于报名人数过多报名失败，请重试！");
						return infoMap;
					}
				}

			}else{
				if(info.getIsperson()==1)
				{
					Integer totalCnt = info.getPersonMaxNum();
					if(rCnt < totalCnt){
						Jedis redis = RedisUtil.getRedis();
						redis.watch(RedisConstants.ACTIVITY+acId);
						Transaction trsn = redis.multi();
						trsn.set(RedisConstants.ACTIVITY+acId, String.valueOf(rCnt));
						List<Object> objList = trsn.exec();
						if(objList != null && objList.size() > 0){
							//下订单
							OrderInfo orderInfo = new OrderInfo();
							
							//查询是否提交过订单
							OrderInfoExample example = new OrderInfoExample();
							com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
							criteria.andTaskInfoIdIsNull();
							criteria.andParamIdEqualTo(acId);
							criteria.andOrderTypeEqualTo(7);
							criteria.andUserIdEqualTo(userId);
							criteria.andOrderStatusEqualTo(0);
							List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(example);
							if(orderInfos.size()>0){
								orderInfo = orderInfos.get(0);
							}
							
							UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
							UserLogin userLogin = userInfo.getUserLogin();
							
							orderInfo.setOrderType(7);//活动订单
							orderInfo.setParamId(acId);
							orderInfo.setUserId(userId);
							
							orderInfo.setOrderStatus(0);
							orderInfo.setAllMoney(info.getAcFee().intValue());
							
							orderInfo.setPayMoney(orderInfo.getAllMoney());
							
							orderInfo.setUserPhone(userLogin.getUserName());
							orderInfo.setOrderTime(new Date());
							
							if(orderInfo.getId() != null){
								if(StringUtils.isBlank(orderInfo.getOrderCode())){
									Integer orderId = orderInfoMapper.insertSelective(orderInfo);
									String code = "";
									code += orderInfo.getOrderType();
									SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
									code += sdf.format(new Date());
									String codeStr = String.valueOf(orderInfo.getId());
									if(codeStr.length()> 6){
										codeStr = codeStr.substring(codeStr.length()-6);
									}else if(codeStr.length() < 6){
										for (int i = 0; i < 6-codeStr.length(); i++) {
											code += "0";
										}
									}
									code += codeStr;
									orderInfo.setOrderCode(code);
									
									/*String code = "139-";
									code += orderInfo.getOrderType()+"-";
									SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
									code += sdf.format(new Date());
									//String num = orderTitleDao.save(title).toString();
									String codeStr = String.valueOf(orderInfo.getId());
									if(codeStr.length()> 5){
										codeStr = codeStr.substring(codeStr.length()-5);
									}
									code += codeStr;
									orderInfo.setOrderCode(code);*/
								}
								orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
							}else {
								Integer orderId = orderInfoMapper.insertSelective(orderInfo);
								String code = "";
								code += orderInfo.getOrderType();
								SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
								code += sdf.format(new Date());
								String codeStr = String.valueOf(orderInfo.getId());
								if(codeStr.length()> 6){
									codeStr = codeStr.substring(codeStr.length()-6);
								}else if(codeStr.length() < 6){
									for (int i = 0; i < 6-codeStr.length(); i++) {
										code += "0";
									}
								}
								code += codeStr;
								orderInfo.setOrderCode(code);
								orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
							}
							infoMap.put("orderIdStr", orderInfo.getId().toString());
							infoMap.put("resultCode", Constants.SUCCESS);
							infoMap.put("resultDesc", Constants.SUCCESS_DESC);						
						}else{
							infoMap.put("resultCode", Constants.FAIL);
							infoMap.put("resultDesc", "由于报名人数过多报名失败，请重试！");
							return infoMap;
						}
					}else{
						infoMap.put("resultCode", Constants.FAIL);
						infoMap.put("resultDesc", "报名人数已经满额，不允许报名！");
						return infoMap;
					}
				}
				else
				{
					Jedis redis = RedisUtil.getRedis();
					redis.watch(RedisConstants.ACTIVITY+acId);
					Transaction trsn = redis.multi();
					trsn.set(RedisConstants.ACTIVITY+acId, String.valueOf(rCnt));
					List<Object> objList = trsn.exec();
					if(objList != null && objList.size() > 0){
						//下订单
						OrderInfo orderInfo = new OrderInfo();
						
						//查询是否提交过订单
						OrderInfoExample example = new OrderInfoExample();
						com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
						criteria.andTaskInfoIdIsNull();
						criteria.andParamIdEqualTo(acId);
						criteria.andOrderTypeEqualTo(7);
						criteria.andUserIdEqualTo(userId);
						criteria.andOrderStatusEqualTo(0);
						List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(example);
						if(orderInfos.size()>0){
							orderInfo = orderInfos.get(0);
						}
						
						UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
						UserLogin userLogin = userInfo.getUserLogin();
						
						orderInfo.setOrderType(7);//活动订单
						orderInfo.setParamId(acId);
						orderInfo.setUserId(userId);
						
						orderInfo.setOrderStatus(0);
						orderInfo.setAllMoney(info.getAcFee().intValue());
						
						orderInfo.setPayMoney(orderInfo.getAllMoney());
						
						orderInfo.setUserPhone(userLogin.getUserName());
						orderInfo.setOrderTime(new Date());
						
						if(orderInfo.getId() != null){
							if(StringUtils.isBlank(orderInfo.getOrderCode())){
								Integer orderId = orderInfoMapper.insertSelective(orderInfo);
								String code = "";
								code += orderInfo.getOrderType();
								SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
								code += sdf.format(new Date());
								String codeStr = String.valueOf(orderInfo.getId());
								if(codeStr.length()> 6){
									codeStr = codeStr.substring(codeStr.length()-6);
								}else if(codeStr.length() < 6){
									for (int i = 0; i < 6-codeStr.length(); i++) {
										code += "0";
									}
								}
								code += codeStr;
								orderInfo.setOrderCode(code);
								
								/*String code = "139-";
								code += orderInfo.getOrderType()+"-";
								SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
								code += sdf.format(new Date());
								//String num = orderTitleDao.save(title).toString();
								String codeStr = String.valueOf(orderInfo.getId());
								if(codeStr.length()> 5){
									codeStr = codeStr.substring(codeStr.length()-5);
								}
								code += codeStr;
								orderInfo.setOrderCode(code);*/
							}
							orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
						}else {
							Integer orderId = orderInfoMapper.insertSelective(orderInfo);
							String code = "";
							code += orderInfo.getOrderType();
							SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
							code += sdf.format(new Date());
							String codeStr = String.valueOf(orderInfo.getId());
							if(codeStr.length()> 6){
								codeStr = codeStr.substring(codeStr.length()-6);
							}else if(codeStr.length() < 6){
								for (int i = 0; i < 6-codeStr.length(); i++) {
									code += "0";
								}
							}
							code += codeStr;
							orderInfo.setOrderCode(code);
							orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
						}
						infoMap.put("orderIdStr", orderInfo.getId().toString());
						infoMap.put("resultCode", Constants.SUCCESS);
						infoMap.put("resultDesc", Constants.SUCCESS_DESC);						
					}else{
						infoMap.put("resultCode", Constants.FAIL);
						infoMap.put("resultDesc", "由于报名人数过多报名失败，请重试！");
						return infoMap;
					}
				}
				
			}
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	@ResponseBody
	@RequestMapping(value="/activity/isReg")
	public Object isReg(HttpServletRequest request,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="acId") String acId
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			ActivityUserExample example = new ActivityUserExample();
			example.createCriteria().andAcIdEqualTo(acId).andUserIdEqualTo(userId);
			List<ActivityUser> list = activityUserMapper.selectByExample(example);
			if(list.size() > 0){
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);	
				infoMap.put("isReg", 1);
			}else{
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);	
				infoMap.put("isReg", 0);
			}
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
		}
		
		return infoMap;
	}
	
	@RequestMapping(value="/activity/resondetail")
	public String resondetail(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="id",required=true) String id,
			@RequestParam(value="pageNow",defaultValue="1",required=false) Integer page,
			@RequestParam(value="pageSize",defaultValue="10",required=false) Integer rows){
		String userId = request.getParameter("userId");
		ActivityUserExample userExample1 = new ActivityUserExample();
		userExample1.createCriteria().andAcIdEqualTo(id);
		Page<?> p = PageHelper.startPage(page,rows);
		userExample1.setOrderByClause("reg_time desc");
		List<ActivityUser> activityUserss = activityUserMapper.selectByExample(userExample1);
		JSONArray array=new JSONArray();
		if(activityUserss.size()>0)
		{
			for(ActivityUser user:activityUserss)
			{
				String configPath = PeiniUtils.IMGHOST;
				UserInfo userinfo=userInfoMapper.selectByPrimaryKey(user.getUserId());
				
				JSONObject obj=new JSONObject();
				
				if(userinfo == null){
					obj.put("name", "");
					obj.put("image","images/ic_nan.png");
				}else{
					obj.put("name", PeiniUtils.updateNickName(userinfo.getNickname(), userinfo.getAccCode()));
					if(userinfo.getImageHead()!=null&&userinfo.getImageHead()!="")
					{
						obj.put("image", configPath+userinfo.getImageHead());
					}
					else
					{
						if(userinfo.getSex()==1)
						{
							obj.put("image","images/ic_nan.png");
						}
						else
						{
							 obj.put("image", "images/ic_nv.png");
						}
					}
				}
				
				array.add(obj);
			}
			
		}
		request.setAttribute("id", id);
		request.setAttribute("userimages", array);
		return "activity/persondetail";
	}
	
	@ResponseBody
	@RequestMapping(value="/activity/resondetailJson")
	public String resondetailJson(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="id",required=true) String id,
			@RequestParam(value="pageNow",defaultValue="1",required=false) Integer page,
			@RequestParam(value="pageSize",defaultValue="10",required=false) Integer rows){
		String userId = request.getParameter("userId");
		JSONObject object=new JSONObject();
		ActivityUserExample userExample1 = new ActivityUserExample();
		userExample1.createCriteria().andAcIdEqualTo(id);
		userExample1.setOrderByClause(" reg_time desc");
		Page<?> p = PageHelper.startPage(page,rows);
		List<ActivityUser> activityUserss = activityUserMapper.selectByExample(userExample1);
		JSONArray array=new JSONArray();
		if(activityUserss.size()>0)
		{
			for(ActivityUser user:activityUserss)
			{
				String configPath = PeiniUtils.IMGHOST;
				UserInfo userinfo=userInfoMapper.selectByPrimaryKey(user.getUserId());
				JSONObject obj=new JSONObject();
				//obj.put("name", userinfo.getNickname());
				obj.put("name", PeiniUtils.updateNickName(userinfo.getNickname(), userinfo.getAccCode()));
				if(userinfo.getImageHead()!=null&&userinfo.getImageHead()!="")
				{
					obj.put("image", configPath+userinfo.getImageHead());
				}
				else
				{
					if(userinfo.getSex()==1)
					{
						obj.put("image","images/ic_nan.png");
					}
					else
					{
						 obj.put("image", "images/ic_nv.png");
					}
				}
				array.add(obj);
			}
			
		}
		object.put("userimages", array);
       return object.toString();
	}
	
	/**
	 * 获取从通知点击的活动链接
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @param id
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/activity/getNotifyLink")
	public Object getNotifyLink(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="id",required=true) String acId,
			@RequestParam(value="userId") String userId){
		
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try {
			Date date=new Date();
			
			com.alibaba.fastjson.JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			String linkStr = "activity/detail?userId="+userId;
			linkStr += "&id="+acId;
			
			ActivityInfo act = activityInfoMapper.selectByPrimaryKey(acId);
			
			if(date.getTime()>act.getSignEndTime().getTime()&&date.getTime()<act.getStartTime().getTime())
			{
				act.setAcStatus(2);
			}
			if(date.getTime()>act.getStartTime().getTime()&&date.getTime()<act.getEndTime().getTime())
			{
				act.setAcStatus(1);
			}
			if(date.getTime()>act.getEndTime().getTime())
			{
				act.setAcStatus(-1);
			}
			
			linkStr += "&status="+act.getAcStatus();
			
			ActivityUserExample example = new ActivityUserExample();
			example.createCriteria().andAcIdEqualTo(acId).andUserIdEqualTo(userId);
			List<ActivityUser> list = activityUserMapper.selectByExample(example);
			if(list.size() > 0){
				linkStr += "&isReg=1";
			}else{
				linkStr += "&isReg=0";
			}
			
			infoMap.put("data", linkStr);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", Constants.SUCCESS_DESC);
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
}
